﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;

namespace WebApi.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class HomeController : ControllerBase
    {
        public static List<string> GetVs = new List<string>() { "dsad", "dasd", "dasdas", "dsad", "dasda" };

        /// <summary>
        /// 授权
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        public List<string> Index()
        {
            var yu = HttpContext.AuthenticateAsync().Result;
            //var auth =HttpContext.auth
            var ww = yu.Principal.Claims.First(t => t.Type.Equals("pwd"))?.Value;
            
            return GetVs.Where(x => x.Length > 2).ToList();
        }
        

        /// <summary>
        /// 不授权
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string GetStrmg() 
        {
            return "123456";
        }

        [AllowAnonymous]
        [HttpGet]
        public string Get(string name, string pwd)
        {
            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
                new Claim(ClaimTypes.Name, "123456789"),
                new Claim("pwd","deasdeade")
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: Const.Domain,  //签发人
                audience: Const.Domain,  //受众
                claims: claims, //
                expires: DateTime.Now.AddMinutes(30),  //过期时间
                signingCredentials: creds);  //签名
            var tok =  new JwtSecurityTokenHandler().WriteToken(token);
            

            return tok;
        }

        [AllowAnonymous]
        [HttpPost]
        public string GetPdf() 
        {
            return "";
        }
    }

    public class Const
    {
        /// <summary>
        /// 这里为了演示，写死一个密钥。实际生产环境可以从配置文件读取,这个是用网上工具随便生成的一个密钥
        /// </summary>
        public const string SecurityKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSW";
        public const string Domain = "http://localhost:5000";
    }
}
